package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiProductionOrderEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ProductionOrderDao;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.ProductionOrderProductEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.product.ProductionOrderFinishProductEnum;
import com.xbongbong.saas.enums.product.ProductionOrderMaterielProductEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.ProductionOrderProductModel;
import com.xbongbong.saas.model.ProductionOrderSubDataModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/25 15:28
 * @since v1.0
 */
@Service("productionOrderModel")
public class ProductionOrderModelImpl implements ProductionOrderModel {
    @Resource
    private ProductionOrderDao productionOrderDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ProductionOrderSubDataModel productionOrderSubDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private ProductionOrderProductModel productionOrderProductModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private SaasFormHelp saasFormHelp;

    @Override
    public Integer insert(ProductionOrderEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = productionOrderDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
        return insert;
    }

    @Override
    public Integer update(ProductionOrderEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = productionOrderDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = productionOrderDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public List<ProductionOrderEntityExt> findEntitys(Map<String, Object> param) {
        List<ProductionOrderEntityExt> entitys = productionOrderDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return productionOrderDao.getEntitysCount(param);
    }

    @Override
    public Integer save(ProductionOrderEntityExt productionOrderEntity) throws XbbException {
        Long id = productionOrderEntity.getId();
        if (id == null || Objects.equals(id, 0L)) {
            return insert(productionOrderEntity);
        }
        return update(productionOrderEntity);
    }

    @Override
    public ProductionOrderEntityExt getByKey(Long key, String corpid) {
        ProductionOrderEntityExt entityExt = productionOrderDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
        return entityExt;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException{
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = productionOrderDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER);
        }
        // todo
        if (!subList.isEmpty()) {
            productionOrderSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatchImmediately(List<UpdateDataEntity> list, String corpid) throws XbbException{
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = productionOrderDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER, WriteRequest.RefreshPolicy.NONE);
        }
        // todo
        if (!subList.isEmpty()) {
            productionOrderSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer deleteBatch(List<Long> list, String corpid) throws XbbException {
        Integer integer = productionOrderDao.deleteBatch(list, corpid);
        paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER);
        paasFormSubDataModel.deleteBatchByDataId(list, corpid, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER);
        paasEsModel.delete(deleteDTO);
        Integer integer = productionOrderDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
        return integer;
    }

    @Override
    public List<AiProductionOrderEntity> getProductionOrderList4Ai(String corpid, List<Long> idIn) {
        return productionOrderDao.getProductionOrderList4Ai(corpid, idIn);
    }

    @Override
    public List<String> getCorpidList() {
        return productionOrderDao.getCorpidList();
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = productionOrderDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER, refreshPolicy);
        }
        // todo
        if (!subList.isEmpty()) {
            productionOrderSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return productionOrderDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        String corpid = formatExplainDTO.getCorpid();
        List<FieldAttrEntity> fieldAttrEntities = formatExplainDTO.getExplainList();
        Integer fromCopy = BasicConstant.ZERO;
        if(formatExplainDTO.getFromCopy() != null){
            // true: 复制1 false：编辑0
            fromCopy = formatExplainDTO.getFromCopy() ? BasicConstant.ONE : BasicConstant.ZERO;
        }
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        boolean unitNoEdit = false;
        if (Objects.nonNull(dataEntity) && !Objects.equals(formatExplainDTO.getFromCopy(), true)) {
            if (CollectionsUtil.isNotEmpty(dataEntity.getData().getJSONArray(ProductionOrderEnum.INSTOCK_ID.getAttr())) ||
                    CollectionsUtil.isNotEmpty(dataEntity.getData().getJSONArray(ProductionOrderEnum.OUTSTOCK_ID.getAttr()))) {
                unitNoEdit = true;
            }
        }
        for (FieldAttrEntity fieldAttrEntity : fieldAttrEntities) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, ProductionOrderEnum.BOM_ID.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, ProductionOrderEnum.PRODUCT.getAttr())) {
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.PRODUCTION_ORDER, corpid, BasicConstant.ONE, unitNoEdit);
            } else if (Objects.equals(attr, ProductionOrderEnum.MATERIEL.getAttr())) {
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.PRODUCTION_ORDER, corpid, BasicConstant.ONE, unitNoEdit);
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result               要返回的jsonObject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, ProductionOrderEnum.BOM_ID.getAttr(), ProductionOrderEnum.BOM_ID_LINK_TEXT.getAttr(), ProductionOrderEnum.BOM_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr(), ProductionOrderEnum.INTO_WAREHOUSE_ID_LINK_TEXT.getAttr(), ProductionOrderEnum.INTO_WAREHOUSE_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr(), ProductionOrderEnum.OUT_WAREHOUSE_ID_LINK_TEXT.getAttr(), ProductionOrderEnum.OUT_WAREHOUSE_ID.getFieldType());
//        formatProduct4Show(result, formDataUpdateGetDTO);

    }

    private void formatProductList(String corpid, List<ProductionOrderProductEntity> productList, JSONObject data, Map<Long, ProductEntityExt> productMap, Integer type) throws XbbException {
        Integer sort = 0;
        JSONArray productArray;
        Long warehouseId = 0L;
        if (Objects.equals(type, 1)) {
            productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, ProductionOrderEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
            // 数据格式是JSONArray
            warehouseId = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr(), new JSONArray()).getJSONObject(0).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
        } else {
            productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, ProductionOrderEnum.MATERIEL.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
        }
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject jsonObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(jsonObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 损耗率
            Double attritionRate = getDoubleOrDefaultFromFormData(jsonObject, RelativeProductEnum.ATTRITION_RATE.getSaasAttr(), 0D);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(jsonObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // BOM清单定义的单位产品数量
            Double productUnitNum = getDoubleOrDefaultFromFormData(jsonObject, RelativeProductEnum.UNIT_NUM.getSaasAttr(), 0D);
            // 备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(jsonObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            // 仓库
            JSONObject warehouse = FastJsonHelper.getJsonObjectFromFormData(jsonObject, RelativeProductEnum.WAREHOUSE.getSaasAttr());
            if (warehouse != null && warehouse.size() > 0 && Objects.equals(type, 2)) {
                warehouseId = FastJsonHelper.getLongOrDefaultFromFormData(warehouse, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            }
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                ProductionOrderProductEntity productEntity = new ProductionOrderProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setType(type);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductUnitNum(productUnitNum);
                productEntity.setAttritionRate(attritionRate);
                productEntity.setProductName(productName);
                productEntity.setProductUnit(unit);
                productEntity.setProductNo(productNo);
                productEntity.setMemo(memo);
                productEntity.setProductSpecification(specification);
                productEntity.setSort(sort);
                //JSONObject productJsonObject = new JSONObject();
                if (Objects.equals(type, 2)) {
                    productEntity.setAttritionRate(attritionRate);
                    //productJsonObject.put(ProductionOrderMaterielProductEnum.LOSS_RATE.getAttr(), attritionRate);
                    //productJsonObject.put(ProductionOrderMaterielProductEnum.WAREHOUSE.getAttr(), warehouseId);
                }
                /*productJsonObject.put(ProductionOrderMaterielProductEnum.PRODUCT.getAttr(), pageProductId);
                productJsonObject.put(ProductionOrderMaterielProductEnum.UNIT.getAttr(), unit);
                productJsonObject.put(ProductionOrderMaterielProductEnum.NUM.getAttr(), productNum);
                productJsonObject.put(ProductionOrderMaterielProductEnum.MEMO.getAttr(), memo);
                productEntity.setData(productJsonObject);*/
                productList.add(productEntity);
            }
        }
    }

    @Override
    public JSONObject formatSingleProduct(ProductionOrderProductEntity productionOrderProductEntity) {
        JSONObject json = productionOrderProductEntity.getData();
        Double rate = showFormatHelp.approvalSetBusinessUnit(json, productionOrderProductEntity);
        if (Objects.equals(productionOrderProductEntity.getType(), 1)) {
            if (Objects.isNull(json) || json.isEmpty()) {
                json = new JSONObject();
                for (ProductionOrderFinishProductEnum productionOrderFinishProductEnum : ProductionOrderFinishProductEnum.values()) {
                    String attr = productionOrderFinishProductEnum.getAttr();
                    switch (productionOrderFinishProductEnum) {
                        case PRODUCT:
                            json.put(attr, productionOrderProductEntity.getProductId());
                            break;
                        case NUM:
                            json.put(attr, productionOrderProductEntity.getProductNum());
                            break;
                        case MEMO:
                            json.put(attr, productionOrderProductEntity.getMemo());
                            break;
                        case UNIT:
                            json.put(attr, productionOrderProductEntity.getProductUnit());
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        return json;
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        // 获取关联产品
        List<ProductionOrderProductEntity> productionOrderProductEntityList = new ArrayList<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(ProductionOrderEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                // 获取成品产品列表
                JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, ProductionOrderEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArray);
                formatProductList(corpid, productionOrderProductEntityList, data, productMap, 1);
                // 获取物料产品列表
                JSONArray materielArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, ProductionOrderEnum.MATERIEL.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> materielMap = productModel.getProductMap(corpid, materielArray);
                formatProductList(corpid, productionOrderProductEntityList, data, materielMap, 2);
            } else {
                JSONArray finishArray = data.getJSONArray(ProductionOrderEnum.PRODUCT.getAttr());
                if (Objects.nonNull(finishArray)) {
                    for (int i = 0; i < finishArray.size(); i++) {
                        JSONObject jsonObject = finishArray.getJSONObject(i);
                        ProductionOrderProductEntity productionOrderProductEntity = new ProductionOrderProductEntity();
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            productionOrderProductEntity.setId(subProductId);
                        }
                        productionOrderProductEntity.setType(1);
                        try {
                            if (data.get(ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr()) instanceof List) {
                                JSONArray warehouseArray = data.getJSONArray(ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr());
                                JSONObject warehouseObj = warehouseArray.getJSONObject(0);
                                Long warehouseId = warehouseObj.getLong("id");
                                productionOrderProductEntity.setWarehouseId(warehouseId);
                            } else {
                                productionOrderProductEntity.setWarehouseId(data.getLong(ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr()));
                            }
                        } catch (Exception e) {
                            JSONArray warehouseArray = data.getJSONArray(ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr());
                            JSONObject warehouseObj = warehouseArray.getJSONObject(0);
                            Long warehouseId = warehouseObj.getLong("id");
                            productionOrderProductEntity.setWarehouseId(warehouseId);
                        }
                        productionOrderProductEntity.setData(jsonObject);
                        productionOrderProductEntity.setProductId(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()));
                        productionOrderProductEntity.setProductUnitNum(jsonObject.getDouble(RelativeProductEnum.UNIT_NUM.getSaasAttr()));
                        productionOrderProductEntityList.add(productionOrderProductEntity);
                    }
                }
                JSONArray materialArray = data.getJSONArray(ProductionOrderEnum.MATERIEL.getAttr());
                if (Objects.nonNull(materialArray)) {
                    for (int i = 0; i < materialArray.size(); i++) {
                        JSONObject jsonObject = materialArray.getJSONObject(i);
                        ProductionOrderProductEntity productionOrderProductEntity = new ProductionOrderProductEntity();
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            productionOrderProductEntity.setId(subProductId);
                        }
                        productionOrderProductEntity.setType(2);
                        productionOrderProductEntity.setWarehouseId(jsonObject.getLong(SelectProductEnum.WAREHOUSE.getAttr()));
                        productionOrderProductEntity.setData(jsonObject);
                        productionOrderProductEntity.setProductId(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()));
                        productionOrderProductEntity.setProductUnitNum(jsonObject.getDouble(RelativeProductEnum.UNIT_NUM.getSaasAttr()));
                        productionOrderProductEntityList.add(productionOrderProductEntity);
                    }
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            productionOrderProductEntityList = productionOrderProductModel.getProductsById(dataId, corpid,null, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
        }
        // 入库应该不会查批次库存，所以注释
        Set<Long> warehouseIdList = new HashSet<>();
        Set<String> warehouseKeySet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productionOrderProductEntityList.forEach(item -> {
            if (Objects.nonNull(item.getWarehouseId())){
                warehouseIdList.add(item.getWarehouseId());
            }
            warehouseKeySet.add(item.getProductId() + "_" + item.getWarehouseId());
        });
        Map<Long, String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!warehouseIdList.isEmpty()) {
            Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID,corpid);
            param.put(StringConstant.DEL,DelEnum.NORMAL.getDel());
            param.put("idIn",warehouseIdList);
            param.put("columns","id,data");
            List<WarehouseEntityExt> warehouseEntityExtList = warehouseModel.findEntitys(param);
//            BoolQueryBuilder boolQueryBuilder = boolQuery();
//            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
//            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),warehouseIdList));
//            boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
//            List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE,boolQueryBuilder,PaasFormDataEntityExt.class, Arrays.asList(FieldTypeEnum.DATAID.getAlias(),WarehouseEnum.getAttrConnectData(WarehouseEnum.WAREHOUSE_NAME)));
            warehouseEntityExtList.forEach(item -> {
                warehouseNameMap.put(item.getId(),item.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
            });
        }
        Map<String, Double> productWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!warehouseKeySet.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
            params.put("warehouseKeyIn",warehouseKeySet);
            List<ProductWarehouseEntity> productWarehouseEntities = productWarehouseModel.findEntitysWithWarehouseChecked(params,null);
            productWarehouseEntities.forEach(item -> {
                productWarehouseMap.put(item.getWarehouseKey(), item.getNum());
            });
        }
        JSONArray productArray = new JSONArray();
        JSONArray materielProductarray = new JSONArray();
        for (ProductionOrderProductEntity productionOrderProductEntity : productionOrderProductEntityList){
            String key = productionOrderProductEntity.getProductId() + "_" + productionOrderProductEntity.getWarehouseId();
            if (Objects.equals(productionOrderProductEntity.getType(),1)){
                JSONObject json = formatSingleProduct(productionOrderProductEntity);
                json.put(ProductionOrderFinishProductEnum.STOCK.getAttr(), productWarehouseMap.getOrDefault(key, 0D));
                if (updateDataTypeEnum.isUpdate()){
                    json.put(BusinessConstant.PRODUCT_SUB_ID,productionOrderProductEntity.getId());
                    if (Objects.isNull(productionOrderProductEntity.getId())) {
                        json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                    }
                }else {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
                if (updateDataTypeEnum.isLinkAdd()){
                    json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(productionOrderProductEntity.getCorpid(),productionOrderProductEntity.getProductUnit()));
                }
                JSONObject warehouseObj = new JSONObject();
                warehouseObj.put("id",productionOrderProductEntity.getWarehouseId());
                warehouseObj.put("name",warehouseNameMap.getOrDefault(productionOrderProductEntity.getWarehouseId(),""));
                // 自定义字段有text_6的关联数据解析 直接put编辑回显会出毛病
//              json.put(SelectProductEnum.WAREHOUSE.getAttr(),Collections.singletonList(warehouseObj));
                json.put("warehouseId",productionOrderProductEntity.getWarehouseId());
                json.put("unitNum",productionOrderProductEntity.getProductUnitNum());
                productArray.add(json);
            }else {
                JSONObject json = productionOrderProductEntity.getData();
                Double rate = showFormatHelp.approvalSetBusinessUnit(json, productionOrderProductEntity);
                if (Objects.isNull(json) || json.isEmpty()) {
                    json = new JSONObject();
                    for (ProductionOrderMaterielProductEnum productionOrderMaterielProductEnum : ProductionOrderMaterielProductEnum.values()) {
                        String attr = productionOrderMaterielProductEnum.getAttr();
                        switch (productionOrderMaterielProductEnum) {
                            case PRODUCT:
                                json.put(attr, productionOrderProductEntity.getProductId());
                                break;
                            case WAREHOUSE:
                                json.put(attr, productionOrderProductEntity.getWarehouseId());
                                break;
                            case NUM:
                                json.put(attr, productionOrderProductEntity.getProductNum());
                                break;
                            case MEMO:
                                json.put(attr, productionOrderProductEntity.getMemo());
                                break;
                            case LOSS_RATE:
                                json.put(attr, productionOrderProductEntity.getAttritionRate());
                                break;
                            case UNIT:
                                json.put(attr, productionOrderProductEntity.getProductUnit());
                                break;
                            default:
                                break;
                        }
                    }
                }
                json.put(ProductionOrderMaterielProductEnum.OUTSTOCK_NUM.getAttr(), Arith.div(productionOrderProductEntity.getOutstockNum(), rate));
                json.put(ProductionOrderMaterielProductEnum.WAIT_OUTSTOCK_NUM.getAttr(), Arith.sub(json.getDouble(ProductionOrderMaterielProductEnum.NUM.getAttr()), json.getDouble(ProductionOrderMaterielProductEnum.OUTSTOCK_NUM.getAttr())));
                json.put(ProductionOrderMaterielProductEnum.STOCK.getAttr(), productWarehouseMap.getOrDefault(key, 0D));
                if (updateDataTypeEnum.isUpdate()){
                    json.put(BusinessConstant.PRODUCT_SUB_ID,productionOrderProductEntity.getId());
                    if (Objects.isNull(productionOrderProductEntity.getId())) {
                        json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                    }
                }else {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
                if (updateDataTypeEnum.isLinkAdd()){
                    json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(productionOrderProductEntity.getCorpid(),productionOrderProductEntity.getProductUnit()));
                }
                JSONObject warehouseObj = new JSONObject();
                warehouseObj.put("id",productionOrderProductEntity.getWarehouseId());
                warehouseObj.put("name",warehouseNameMap.getOrDefault(productionOrderProductEntity.getWarehouseId(),""));
                json.put(ProductionOrderMaterielProductEnum.WAREHOUSE.getAttr(),Collections.singletonList(warehouseObj));
                json.put("warehouseId",productionOrderProductEntity.getWarehouseId());
                json.put("unitNum",productionOrderProductEntity.getProductUnitNum());
                json.put("refId",productionOrderProductEntity.getId());
                materielProductarray.add(json);
            }
        }
//        // 生产单审批，老数据没有保存库存数量，需要实时查询关联产品数据
//        for (Object object : productArray) {
//            JSONObject jsonObject = (JSONObject)object;
//            Long productId = jsonObject.getLong(ProductionOrderFinishProductEnum.PRODUCT.getAttr());
//            Long warehouseId = jsonObject.getLong("warehouseId");
//            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//            params.put("del", DelEnum.NORMAL.getDel());
//            params.put(ParameterConstant.CORPID, corpid);
//            params.put("productId", productId);
//            params.put("warehouseId", warehouseId);
//            List<ProductWarehouseEntity> productWarehouseEntities = productWarehouseModel.findEntitys(params);
//            jsonObject.put(ProductionOrderFinishProductEnum.STOCK.getAttr(), 0D);
//            if (!productWarehouseEntities.isEmpty()) {
//                ProductWarehouseEntity productWarehouseEntity = productWarehouseEntities.get(0);
//                jsonObject.put(ProductionOrderFinishProductEnum.STOCK.getAttr(), productWarehouseEntity.getNum());
//            }
//        }
//        // 物料产品
//        for (Object object : materielProductarray) {
//            JSONObject jsonObject = (JSONObject)object;
//            Long productId = jsonObject.getLong(ProductionOrderMaterielProductEnum.PRODUCT.getAttr());
//            Long warehouseId = jsonObject.getLong("warehouseId");
//            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//            params.put("del", DelEnum.NORMAL.getDel());
//            params.put(ParameterConstant.CORPID, corpid);
//            params.put("productId", productId);
//            params.put("warehouseId", warehouseId);
//            List<ProductWarehouseEntity> productWarehouseEntities = productWarehouseModel.findEntitys(params);
//            jsonObject.put(ProductionOrderFinishProductEnum.STOCK.getAttr(), 0D);
//            if (!productWarehouseEntities.isEmpty()) {
//                ProductWarehouseEntity productWarehouseEntity = productWarehouseEntities.get(0);
//                jsonObject.put(ProductionOrderMaterielProductEnum.STOCK.getAttr(), productWarehouseEntity.getNum());
//            }
//        }
        data.put(ProductionOrderEnum.PRODUCT.getAttr(),productArray);
        data.put(ProductionOrderEnum.MATERIEL.getAttr(),materielProductarray);
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = productionOrderDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER);
        paasEsModel.update(insertDTO);
        return success;
    }
}
